<template>
  <div class="game-prize">
    <div class="back-box">
      <span @click="backPageHandle" class="back-btn"><i class="el-icon-back"></i>返回</span>
      <span>&nbsp;&nbsp;|&nbsp;&nbsp;</span>
      <span>游戏奖品管理</span>
    </div>
    <transition name="el-zoom-in-top">
      <el-form v-show="searchFormVisible" inline size="mini" :model="searchForm" ref="searchForm" @keyup.enter.native="searchHandle">
        <el-form-item prop="word" label="游戏奖品检索">
          <el-input v-model="searchForm.word" clearable placeholder="请输入游戏奖品名称"></el-input>
        </el-form-item>
        <el-form-item prop="status">
          <el-select v-model="searchForm.status" clearable placeholder="请选择状态">
            <el-option v-for="statusEnum in statusEnumList" :key="'status' + statusEnum.value"
                       :label="statusEnum.name" :value="statusEnum.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button :disabled="dataLoad" @click="searchHandle" type="primary" icon="el-icon-search">查询</el-button>
          <el-button :disabled="dataLoad" @click="resetFormHandle" plain icon="el-icon-refresh-right">重置</el-button>
        </el-form-item>
      </el-form>
    </transition>
    <div class="g-p-tool">
      <el-button :disabled="dataLoad" @click="$refs.gamePrizeDialog.initDialog(undefined, searchForm.gameId)"
                 type="primary" size="mini" plain icon="el-icon-plus">添加</el-button>
      <el-button :disabled="gamePrizeSelection.length !== 1 || dataLoad || buttonLoad" @click="saveDefaultPrizeHandle"
                 type="primary" size="mini" plain icon="el-icon-edit">设为默认</el-button>
      <el-tooltip class="item" effect="light" content="初始化游戏奖品池缓存" placement="top">
        <el-button :disabled="totalProbability % 10 !== 0 || dataLoad || buttonLoad" @click="initGamePrizePoolHandle"
                   type="success" size="mini" plain icon="el-icon-open">初始化</el-button>
      </el-tooltip>
      <el-button :disabled="gamePrizeSelection.length === 0 || dataLoad || buttonLoad" @click="updateGamePrizeStatusHandle(undefined, 0)"
                 type="success" size="mini" plain icon="el-icon-circle-plus-outline">启用</el-button>
      <el-button :disabled="gamePrizeSelection.length === 0 || dataLoad || buttonLoad" @click="updateGamePrizeStatusHandle(undefined, 1)"
                 type="warning" size="mini" plain icon="el-icon-circle-close">禁用</el-button>
      <el-button :disabled="gamePrizeSelection.length === 0 || dataLoad || buttonLoad" @click="deleteGamePrizeHandle(undefined)"
                 type="danger" size="mini" plain icon="el-icon-delete">删除</el-button>
      <el-button v-show="defaultPrizeId !== '0'" :disabled="gamePrizeSelection.length !== 1 || dataLoad || buttonLoad"
                 @click="deleteDefaultPrizeHandle(undefined)"
                 type="danger" size="mini" plain icon="el-icon-delete">取消默认</el-button>
    </div>
    <div class="g-p-tool">
      <span>当前奖品总概率:<span class="probability" :class="[totalProbability % 10 === 0 ? 'success' : 'warning']">{{ totalProbability }}</span></span>

      <right-tool-bar :search-visible="searchFormVisible" :search-load="dataLoad"
                      @toggle-search="searchFormVisible = !searchFormVisible" @refresh-table="getGamePrizeList" />
    </div>
    <el-table
      v-loading="dataLoad"
      element-loading-text="游戏奖品数据加载中..."
      element-loading-spinner="el-icon-loading"
      :data="gamePrizeList"
      @sort-change="sortChangeHandle"
      @selection-change="(val) => this.gamePrizeSelection = val"
      ref="gamePrizeTable"
    >
      <el-table-column type="selection" header-align="center" align="center" width="50"></el-table-column>
      <el-table-column sortable="custom" :sort-orders="sortOrders" prop="prizeName" header-align="center" align="center" label="奖品名称" min-width="100"></el-table-column>
      <el-table-column prop="prizeValue" header-align="center" align="center" label="具体奖品"></el-table-column>
      <el-table-column prop="prizeTotalNum" header-align="center" align="center" label="奖品总数"></el-table-column>
      <el-table-column prop="prizeUseNum" header-align="center" align="center" label="已使用数"></el-table-column>
      <el-table-column prop="probability" header-align="center" align="center" label="中奖概率"></el-table-column>
      <el-table-column sortable="custom" :sort-orders="sortOrders" prop="sort" header-align="center" align="center" label="排序等级" width="100"></el-table-column>
      <el-table-column header-align="center" align="center" label="默认奖品">
        <template v-slot="{row}">
          <el-tag :type="row.id === defaultPrizeId ? 'success' : 'info'">
            {{ row.id === defaultPrizeId ? '是' : '否' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="status" header-align="center" align="center" label="状态">
        <template v-slot="{row}">
          <el-tag :type="row.status === 0 ? 'primary' : 'danger'">
            {{ row.status | baseFormat(statusEnumList) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="remark" header-align="center" align="center" label="备注"></el-table-column>
      <el-table-column sortable="custom" :sort-orders="sortOrders" prop="createTime" header-align="center" align="center" label="创建时间" width="135"></el-table-column>
      <el-table-column prop="createUser" header-align="center" align="center" label="创建用户"></el-table-column>
      <el-table-column
        header-align="left"
        width="150"
        label="操作">
        <template v-slot="{ row }">
          <div>
            <el-button type="text" icon="el-icon-edit" @click="$refs.gamePrizeDialog.initDialog(row, searchForm.gameId)">
              修改
            </el-button>
            <el-button v-if="row.status === 1" type="text" icon="el-icon-check" @click="updateGamePrizeStatusHandle(row, 0)">
              启用
            </el-button>
            <el-button v-if="row.status === 0" type="text" icon="el-icon-close" @click="updateGamePrizeStatusHandle(row, 1)">
              禁用
            </el-button>
          </div>
          <div>
            <el-button type="text" icon="el-icon-delete" @click="deleteGamePrizeHandle(row)" class="danger-color">
              删除
            </el-button>
            <el-button type="text" icon="el-icon-view" @click="$refs.prizeFlowDialog.initDialog(row.id, 0)">
              流水
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :disabled="dataLoad"
      :current-page="searchForm.page"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="searchForm.limit"
      :total="totalNum"
      layout="total, sizes, prev, pager, next, jumper"
      class="paging">
    </el-pagination>

    <!-- 游戏奖品添加/修改弹出框 -->
    <game-prize-dialog ref="gamePrizeDialog" @refresh-table="getGamePrizeList" />

    <!-- 游戏奖品流水弹出框 -->
    <prize-flow-dialog ref="prizeFlowDialog" />
  </div>
</template>

<script>
  import RightToolBar from "@/components/common/right-toolbar";
  import GamePrizeDialog from "@/components/game/prize/save-update";
  import PrizeFlowDialog from "@/components/game/flow";
  export default {
    name: "admin-game-prize",
    layout: 'admin',
    components: {
      RightToolBar, GamePrizeDialog, PrizeFlowDialog,
    },
    data() {
      return {
        // 游戏奖品列表
        gamePrizeList: [],
        // 选中的游戏数据
        gamePrizeSelection: [],
        // 游戏奖品总数
        totalNum: 0,
        // 所有游戏奖品总中奖概率
        totalProbability: 0,
        // 游戏默认奖品主键
        defaultPrizeId: undefined,
        // 状态枚举列表
        statusEnumList: [
          {
            name: '可用',
            value: 0
          },
          {
            name: '不可用',
            value: 1
          }
        ],
        // 表格排序字段排序方式
        sortOrders: ['ascending', 'descending'],
        // 游戏奖品管理检索表单显示状态[true-显示 false-隐藏]
        searchFormVisible: true,
        // 游戏奖品管理检索表单对象
        searchForm: {
          // 游戏主键
          gameId: undefined,
          // 游戏奖品名称
          word: '',
          // 状态
          status: '',
          // 当前展示页码
          page: 1,
          // 当前页显示个数
          limit: 10,
          // 排序字段
          field: 'id',
          // 排序方式
          order: 'descending'
        },
        // 数据加载状态[false-不加载 true-加载]
        dataLoad: false,
        // 按钮禁用状态[true-禁用 false-可用]
        buttonLoad: false,
        // 游戏管理页面检索参数
        prePageSearchForm: '',
      }
    },
    filters: {
      /**
       * 枚举映射方法
       * @param {number} value 参数值
       * @param {Array}  list  枚举列表
       */
      baseFormat(value, list) {
        for (let obj of list) {
          if (obj.value === value) {
            return obj.name;
          }
        }
        return '未知';
      }
    },
    asyncData({ app, params } ) {
      if (!params.gameId) {
        app.router.replace('/admin/game');
        return;
      }
      // console.log('params', params);
      let data = {
        gameId: params.gameId,
        page: 1,
        limit: 10,
        field: 'id',
        order: 'descending'
      }
      return app.$axios.$post('/game-prize/page/list', data)
        .then(({ data }) => {
          let page = data.page;
          return {
            gamePrizeList: page.list,
            totalNum: page.totalNum,
            totalProbability: data.totalProbability,
            defaultPrizeId: data.defaultPrizeId,
            searchForm: {
              gameId: params.gameId,
              word: '',
              status: '',
              page: 1,
              limit: 10,
              field: 'id',
              order: 'descending'
            },
            prePageSearchForm: params.prePageSearchForm
          }
        })
        .catch(() => {});
    },
    methods: {
      /**
       * 回退到游戏管理页面
       */
      backPageHandle() {
        this.$router.replace({name: 'admin-game', params: { searchForm: this.prePageSearchForm }});
      },
      /**
       * 查询游戏奖品事件
       */
      searchHandle() {
        this.searchForm.page = 1;

        this.getGamePrizeList();
      },
      /**
       * 获取游戏奖品列表方法
       */
      getGamePrizeList() {
        // 开始加载
        this.dataLoad = true;
        this.$axios.$post('/game-prize/page/list', this.searchForm)
          .then(({ data }) => {
            let page = data.page;
            this.gamePrizeList = page.list;
            this.totalNum = page.totalNum;
            this.totalProbability = data.totalProbability;
            this.defaultPrizeId = data.defaultPrizeId;
          })
          .catch(() => {})
          .finally(() => {
            // 加载结束
            this.dataLoad = false;
          })
      },
      /**
       * 保存游戏默认奖品事件
       */
      saveDefaultPrizeHandle() {
        let gamePrize = this.gamePrizeSelection[0];
        if (gamePrize.id === this.defaultPrizeId) {
          this.notify('', '温馨提示', '您要设置的奖品已是游戏默认奖品，请确认');
          return
        }
        // 按钮禁用
        this.buttonLoad = true;
        this.$confirm(`您确定将‘${gamePrize.prizeName}’设置成默认奖品吗, 是否继续?`, '操作提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
            let data = {
              gameId: this.searchForm.gameId,
              prizeId: gamePrize.id,
              oldPrizeId: this.defaultPrizeId
            }
            return this.$axios.$post('/game/save/defaultPrize', data)
          })
          .then(() => {
            this.notify('success', '操作成功', '设置游戏默认奖品操作成功');
            // 更新默认奖品主键
            this.defaultPrizeId = gamePrize.id;
            // 清空表格选中数据
            this.$refs.gamePrizeTable.clearSelection();
          })
          .catch(() => {})
          .finally(() => {
            // 按钮恢复可点击
            this.buttonLoad = false;
          });
      },
      /**
       * 初始化游戏奖品池缓存事件
       */
      initGamePrizePoolHandle() {
        // 按钮禁用
        this.buttonLoad = true;
        this.$axios.$post('/game-prize/init/pool', { gameId: this.searchForm.gameId })
          .then(() => {
            this.notify('success', '操作成功', '初始化游戏奖品池操作成功');
          })
          .catch(() => {})
          .finally(() => {
            // 按钮恢复可使用
            this.buttonLoad = false;
          })
      },
      /**
       * 更新游戏奖品状态事件
       * @param {Object} gamePrize 游戏奖品对象
       * @param {number} newStatus 新状态
       */
      updateGamePrizeStatusHandle(gamePrize, newStatus) {
        let data = {
          gameId: this.searchForm.gameId,
          idList: [],
          status: newStatus
        }
        let message;
        if (gamePrize) {
          // 单个
          data.idList.push(gamePrize.id);
          message = `您确定要‘${newStatus === 0 ? '启用' : '禁用'}’${gamePrize.prizeName}游戏奖品吗，是否继续？`
        } else {
          // 批量
          data.idList = this.gamePrizeSelection.filter(_gamePrize => _gamePrize.status !== newStatus).map(_gamePrize => _gamePrize.id);
          if (data.idList.length === 0) {
            this.notify('', '温馨提示', `您选中的数据无需进行’${newStatus === 0 ? '启用' : '禁用'}‘操作`);
            return
          }
          message = `您确定要批量‘${newStatus === 0 ? '启用' : '禁用'}’游戏奖品吗，是否继续？`
        }
        this.$confirm(message, '操作提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
            // 按钮禁用
            this.buttonLoad = true;
            return this.$axios.$post('/game-prize/update/status', data);
          })
          .then(() => {
            let successMessage;
            if (gamePrize) {
              successMessage = `‘${newStatus === 0 ? '启用' : '禁用'}’${gamePrize.prizeName}游戏奖品操作成功`;
              // 更新状态
              gamePrize.status = newStatus;
              // 总中奖概率加上/减去奖品的中奖概率
              this.totalProbability += newStatus === 0 ? gamePrize.probability : -gamePrize.probability;
            } else {
              successMessage = `批量‘${newStatus === 0 ? '启用' : '禁用'}’游戏奖品操作成功`;
              // 更新状态
              this.gamePrizeSelection.forEach(_gamePrize => {
                if (_gamePrize.status !== newStatus) {
                  // 总中奖概率加上/减去奖品的中奖概率
                  this.totalProbability += newStatus === 0 ? _gamePrize.probability : -_gamePrize.probability;
                }
                _gamePrize.status = newStatus
              });
              // 清空表格选中数据
              this.$refs.gamePrizeTable.clearSelection();
            }
            this.notify('success', '操作成功', successMessage);
          })
          .catch(err => {
            if (err.code === 409) {
              this.getGamePrizeList();
            }
          })
          .finally(() => {
            // 按钮恢复可使用
            this.buttonLoad = false;
          });
      },
      /**
       * 删除游戏奖品事件
       * @param {Object} gamePrize 游戏奖品对象
       */
      deleteGamePrizeHandle(gamePrize) {
        let data = {
          gameId: this.searchForm.gameId,
          idList: undefined,
        }
        let message;
        if (gamePrize) {
          // 单个删除
          data.idList = [ gamePrize.id ];
          message = `您确定要删除‘${gamePrize.prizeName}’游戏奖品吗，是否继续？`
        } else {
          // 批量删除
          data.idList = this.gamePrizeSelection.map(game => game.id);
          message = '您确定要删除选中的游戏奖品吗，是否继续？'
        }
        this.$confirm(message, '操作提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'danger'
        }).then(() => {
            // 按钮禁用
            this.buttonLoad = true;
            return this.$axios.$delete('/game-prize/delete', { data: data });
          })
          .then(() => {
            this.notify('success', '操作成功', '游戏奖品删除成功');
            // 刷新表格
            this.getGamePrizeList();
          })
          .catch(err => {
            if (err.code === 409) {
              this.getGamePrizeList();
            }
          })
          .finally(() => {
            // 按钮恢复可使用
            this.buttonLoad = false;
          });
      },
      /**
       * 删除游戏默认奖品事件
       */
      deleteDefaultPrizeHandle() {
        let gamePrize = this.gamePrizeSelection[0];
        if (gamePrize.id !== this.defaultPrizeId) {
          this.notify('', '温馨提示', '您要取消的奖品不是游戏默认奖品，请确认')
          return
        }
        // 按钮禁用
        this.buttonLoad = true;
        this.$confirm(`您确定取消‘${gamePrize.prizeName}’默认奖品吗, 是否继续?`, '操作提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let data = {
            gameId: this.searchForm.gameId,
            oldPrizeId: this.defaultPrizeId
          }
          return this.$axios.$delete('/game/delete/defaultPrize', { data: data })
        })
          .then(({ data }) => {
            this.notify('success', '操作成功', '取消游戏默认奖品操作成功');
            // 更新默认奖品主键
            this.defaultPrizeId = data;
            // 清空表格选中数据
            this.$refs.gamePrizeTable.clearSelection();
          })
          .catch(() => {})
          .finally(() => {
            // 按钮恢复可点击
            this.buttonLoad = false;
          });
      },
      /**
       * 表格选择字段排序事件
       * @param {string} prop  排序字段
       * @param {string} order 排序方式
       */
      sortChangeHandle( { prop, order } ) {
        this.searchForm.page = 1;
        this.searchForm.field = prop;
        this.searchForm.order = order;

        this.getGamePrizeList();
      },
      /**
       * 每页显示个数变化事件
       * @param {number} size 最新显示个数值
       */
      sizeChangeHandle(size) {
        let searchForm = this.searchForm;
        searchForm.page = 1;
        searchForm.limit = size;
        this.getGamePrizeList();
      },
      /**
       * '点击特定页码'、'上一页'、'下一页'操作事件
       * @param {number} index 最新页码
       */
      currentChangeHandle(index) {
        let searchForm = this.searchForm;
        if (searchForm.page === index) {
          return;
        }
        searchForm.page = index;
        this.getGamePrizeList();
      },
      /**
       * 重置检索表单对象事件
       */
      resetFormHandle() {
        // 重置表单
        this.$refs.searchForm.resetFields();

        this.searchForm.page = 1;
      },
    }
  }
</script>

<style scoped>
  .game-prize .back-box {
    font-size: 14px;
    height: 35px;
    line-height: 35px;
    margin-bottom: 7px;
  }
  .game-prize .back-box .back-btn {
    height: 100%;
    cursor: pointer
  }
  .game-prize .back-box .back-btn:hover {
    background-color: #F2F6FC;
  }
  .game-prize .g-p-tool {
    margin-bottom: 10px;
  }
  .game-prize .g-p-tool .probability {
    margin-left: 10px;
  }
  .game-prize .g-p-tool .probability.success {
    color: #71e2a3;
  }
  .game-prize .g-p-tool .probability.warning {
    color: #ffd666;
  }
  .game-prize .paging {
    float: right;
    margin: 7px;
  }
</style>
